package com.ruoyi.web.controller.minglvmini;


import com.github.pagehelper.Page;
import com.minglv.mini.domain.*;
import com.minglv.mini.domain.dto.InformationDto;
import com.minglv.mini.domain.dto.MemberVerifyLawyerVo;
import com.minglv.mini.domain.dto.RecommendParVo;
import com.minglv.mini.domain.dto.UserDto;
import com.minglv.mini.service.*;
import com.minglv.mini.tools.DateUtil;
import com.minglv.mini.tools.JWTUtils;
import com.minglv.mini.tools.MiniResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "API-我的")
@RestController
@RequestMapping("/api/user")
public class ApiUserController {

    @Resource
    IUserFavoritesService userFavoritesService;

    @Resource
    IUserService userService;

    @Resource
    IUserInformationService userInformationService;

    @Resource
    IActivityApplyService activityApplyService;

    @Resource
    IActivityService activityService;

    @Resource
    INeedService needService;

    @Resource
    IOrderService orderService;

    @Resource
    private IRecommendMonthParService recommendMonthParService;

    @Resource
    private IRecommendParService recommendParService;

    @Autowired
    private IMemberVerifyLawyerService memberVerifyLawyerService;

    @ApiOperation("我的推荐-个人申报")
    @GetMapping("/memberVerifyLawyer/list")
    public Object getMemberVerifyLawyer(HttpServletRequest request,
                                        @RequestParam(name = "status", required = false)
                                        @ApiParam(value = "审核状态：0待审核, 1已通过, 2被拒绝;为空查询全部") Integer status) {
        String token = request.getHeader("token");
        if (!checkToken(token)) {
            Map reMap = new HashMap();
            reMap.put("code", 401);
            reMap.put("msg", "Token过期,或无此用户");
            return reMap;
        }

        token = token.replace(Constants.TOKEN_PREFIX, "");
        Long userId = JWTUtils.getUserid(token);
        MemberVerifyLawyer memberVerifyLawyer = new MemberVerifyLawyer();
        memberVerifyLawyer.setUserId(userId);
//        memberVerifyLawyer.setIsCheck(isCheck);
        memberVerifyLawyer.setStatus(status);
        List<MemberVerifyLawyer> memberVerifyLawyers = memberVerifyLawyerService.selectMemberVerifyLawyerList(memberVerifyLawyer);
        List<MemberVerifyLawyerVo> memberVerifyLawyerVos = new java.util.ArrayList<>();
        if (!memberVerifyLawyers.isEmpty()) {
            for (MemberVerifyLawyer verifyLawyer : memberVerifyLawyers) {
                MemberVerifyLawyerVo vo = new MemberVerifyLawyerVo();
                BeanUtils.copyProperties(verifyLawyer, vo);
                vo.setCreateTime(DateUtil.parseDate(verifyLawyer.getCreateTime()));
                memberVerifyLawyerVos.add(vo);
            }
        }
        Map data = new HashMap();
        data.put("list", memberVerifyLawyerVos);
        data.put("count", memberVerifyLawyerVos.size());

        return MiniResult.success(data);

    }

    @ApiOperation("我的推荐-奖项申请")
    @GetMapping("/recommendMonthPar/list")
    public Object getRecommendMonthParList(HttpServletRequest request,
                                           @RequestParam(name = "status", required = false)
                                           @ApiParam(value = "审核状态：0待审核, 1已通过, 2被拒绝;为空查询全部") Integer status) {
        String token = request.getHeader("token");
        if (!checkToken(token)) {
            Map reMap = new HashMap();
            reMap.put("code", 401);
            reMap.put("msg", "Token过期,或无此用户");
            return reMap;
        }

        token = token.replace(Constants.TOKEN_PREFIX, "");
        Long userId = JWTUtils.getUserid(token);
        RecommendMonthPar rp = new RecommendMonthPar();
        rp.setUserId(userId);
        rp.setStatus(status);
        List<RecommendMonthPar> list = recommendMonthParService.selectRecommendMonthParList(rp);
        Map data = new HashMap();
        data.put("list", list);
        data.put("count", list.size());
        return MiniResult.success(data);
    }

    @ApiOperation("我的推荐-年度推荐")
    @GetMapping("/recommendPar/list")
    public Object getRecommendParList(HttpServletRequest request,
                                      @RequestParam(name = "status", required = false)
                                      @ApiParam(value = "审核状态：0待审核, 1已通过, 2被拒绝;为空查询全部") Integer status) {
        String token = request.getHeader("token");
        if (!checkToken(token)) {
//            return MiniResult.fail(401, "Token过期,或无此用户");
            Map reMap = new HashMap();
            reMap.put("code", 401);
            reMap.put("msg", "Token过期,或无此用户");
            return reMap;
        }

        token = token.replace(Constants.TOKEN_PREFIX, "");
        Long userId = JWTUtils.getUserid(token);
        RecommendPar rp = new RecommendPar();
        rp.setUserId(userId);
        rp.setStatus(status);
        List<RecommendPar> list = recommendParService.selectRecommendParList(rp);
        List<RecommendParVo> listVo = new java.util.ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (RecommendPar recommendPar : list) {
                RecommendParVo vo = new RecommendParVo();
                BeanUtils.copyProperties(recommendPar, vo);
                vo.setCreateTime(DateUtil.parseDate(recommendPar.getCreateTime()));
                listVo.add(vo);
            }
        }
        Map data = new HashMap();
        data.put("list", listVo);
        data.put("count", listVo.size());
        return MiniResult.success(data);
    }

    @PostMapping("/order/cancel")
    @ApiOperation("取消兑换")
    public Object postOrderCancel(@RequestParam(name = "id") Long id){
        ActivityApply activityApply = activityApplyService.selectActivityApplyById(id);
        if (!ObjectUtils.isEmpty(activityApply)) {
            activityApply.setStatus(3);
        }
        return new MiniResult(200,"操作成功",null);
    }

    @GetMapping("/order/list")
    @ApiOperation("兑换记录")
    public Object getOrderList(HttpServletRequest request,
                               @RequestParam(name = "page") Integer page
                               ){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        String[] s = token.split(" ");
        token = s[1];
        Long userId = JWTUtils.getUserid(token);
        Page<Object> objects = PageUtils.startPage(page, 10);
        List<Map> list = orderService.getOrderList(userId);
        Map data = new HashMap();
        data.put("list",list);
        data.put("count",objects.getTotal());
        return MiniResult.success(data);

    }

    @GetMapping("/active/qrcode")
    @ApiOperation("活动码")
    public MiniResult getQrcode(@RequestParam(name = "id") Long id){
        return MiniResult.success(activityApplyService.getQrcode(id));
    }

    @GetMapping("/need/info")
    @ApiOperation("用户需求详情")
    public MiniResult getNeedInfo(@RequestParam(name = "id") Long id){
        return MiniResult.success(needService.getNeedInfo(id));
    }


    @PostMapping("/need/del")
    @ApiOperation("删除需求")
    public MiniResult postDelete(@RequestBody Map parm) {
        needService.deleteNeedById(Long.valueOf(parm.get("id").toString()));
        return new MiniResult(200,"删除成功",null);
    }

    @GetMapping("/need/list")
    @ApiOperation("我的需求列表")
    public Object getNeedList(HttpServletRequest request, @RequestParam(name = "page") Integer page,@RequestParam(name = "status",required = false)Integer status){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        String[] s = token.split(" ");
        token = s[1];
        Long userId = JWTUtils.getUserid(token);
        Page<Object> objects = PageUtils.startPage(page, 10);
        List<Map> list = needService.getNeedsByUserId(userId, status);
        Map data = new HashMap();
        data.put("list",list);
        data.put("count",objects.getTotal());
        return MiniResult.success(data);
    }

    @GetMapping("/active/info")
    @ApiOperation("活动详情")
    public MiniResult getActiveInfo(@RequestParam(name = "id") Long id){
        return MiniResult.success(activityApplyService.getActiveInfo(id));
    }

    @GetMapping("/active/list")
    @ApiOperation("我的活动列表")
    public Object getActiveList(HttpServletRequest request, @RequestParam(name = "page") Integer page,@RequestParam(name = "status",required = false) Integer status){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }

        String[] s = token.split(" ");
        token = s[1];
        Long userId = JWTUtils.getUserid(token);
        Page<Object> objects = PageUtils.startPage(page, 10);
        List<Map> list = activityService.getListbyUserId(status, userId);
        Map data = new HashMap();
        data.put("list",list);
        data.put("count",objects.getTotal());
        return MiniResult.success(data);
    }

    @PostMapping("/active/sign")
    @ApiOperation("活动签到")
    public Object postActiveSign(HttpServletRequest request, @RequestParam(name = "code") String code){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }

       return MiniResult.success(activityApplyService.postActiveSign(token,code));

    }

    @PostMapping("/information/save")
    @ApiOperation("保存详细资料")
    public Object postInformation(HttpServletRequest request, @RequestBody InformationDto informationDto){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        return userInformationService.postInformation(token,informationDto);
    }

    @GetMapping("/collect/list")
    @ApiOperation("我的收藏")
    public Object getCollect(HttpServletRequest request, @RequestParam(name = "page") Integer page,@RequestParam(name = "type") Integer type){
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            String[] s = token.split(" ");
            if (!ObjectUtils.isEmpty(s) && s.length > 0) {
                token = s[1];
                Long userId = JWTUtils.getUserid(token);
                if (ObjectUtils.isEmpty(userId)) {
                    Map reMap = new HashMap();
                    reMap.put("code",401);
                    reMap.put("msg","Token过期,或无此用户");
                    return reMap;
                }else{
                    List<Map> reMap = null;
                    Page<Object> objects = null;
                    if (type == 1) {
                        objects = PageUtils.startPage(page, 10);
                        reMap = userFavoritesService.getFavoritesActivityList(userId);
                    }else{
                        objects = PageUtils.startPage(page, 10);
                        reMap = userFavoritesService.getFavoritesGoodsList(userId);
                    }

                    Map data = new HashMap();
                    data.put("list",reMap);
                    data.put("count",objects.getTotal());
                    return MiniResult.success(data);
                }
            }else{
                Map reMap = new HashMap();
                reMap.put("code",401);
                reMap.put("msg","Token过期,或无此用户");
                return reMap;
            }
        }else{
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
    }

    @GetMapping("/info")
    @ApiOperation("用户信息")
    public Object getInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        String[] s = token.split(" ");
        token = s[1];
        Long userId = JWTUtils.getUserid(token);

        return MiniResult.success(userService.getInfo(userId));


    }

    @PostMapping("/save")
    @ApiOperation("保存")
    public Object postSave(HttpServletRequest request, @RequestBody UserDto userDto){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        token = token.replace(Constants.TOKEN_PREFIX, "");
        return userService.postSave(token,userDto);
    }

    @GetMapping("/information")
    @ApiOperation("用户信息")
    public Object getInformation(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!checkToken(token)) {
            Map reMap = new HashMap();
            reMap.put("code", 401);
            reMap.put("msg", "Token过期,或无此用户");
            return reMap;
        }

        token = token.replace(Constants.TOKEN_PREFIX, "");
        return MiniResult.success(userInformationService.getInformation(token));
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    Boolean checkToken(String token){
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        String[] s = token.split(" ");
        if (ObjectUtils.isEmpty(s) || s.length == 0) {
            return false;
        }

        token = s[1];
        Long userId = JWTUtils.getUserid(token);
        if (ObjectUtils.isEmpty(userId)) {
            return false;
        }

        User user = userService.selectUserById(userId);
        if (ObjectUtils.isEmpty(user)) {
            return false;
        }
        return true;
    }

}
